<template>
  <div class="team-detail" v-loading="teamStore.loading">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button :icon="ArrowLeft" @click="goBack">
          {{ $t('common.back') }}
        </el-button>
        <div class="team-info">
          <div class="team-avatar">
            <el-avatar 
              :size="64" 
              :src="currentTeam?.teamAvatarUrl"
              :icon="UserFilled"
            >
              {{ currentTeam?.name?.charAt(0).toUpperCase() }}
            </el-avatar>
          </div>
          <div class="team-meta">
            <h1 class="team-name">{{ currentTeam?.name }}</h1>
            <div class="team-status">
              <el-tag :type="getTeamStatusType(currentTeam?.status)">
                {{ getTeamStatusLabel(currentTeam?.status) }}
              </el-tag>
              <span class="member-count">
                {{ currentTeam?.currentMembers }}/{{ currentTeam?.maxMembers }} {{ $t('team.members') }}
              </span>
            </div>
          </div>
        </div>
      </div>
      <div class="header-right">
        <el-button 
          v-if="canManage"
          :icon="Edit" 
          @click="showEditDialog = true"
        >
          {{ $t('common.edit') }}
        </el-button>
        <el-button
          v-if="canManage"
          :icon="User"
          @click="showInviteDialog = true"
        >
          {{ $t('team.inviteMembers') }}
        </el-button>
        <el-dropdown v-if="canManage" trigger="click" @command="handleCommand">
          <el-button :icon="MoreFilled">
            {{ $t('common.more') }}
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="settings" :icon="Setting">
                {{ $t('team.teamSettings') }}
              </el-dropdown-item>
              <el-dropdown-item 
                command="delete" 
                :icon="Delete"
                v-if="canDelete"
                divided
              >
                {{ $t('common.delete') }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 待审核提示 -->
    <el-alert
      v-if="currentTeam?.status === 'PENDING'"
      :title="$t('team.pendingApprovalTitle')"
      :description="$t('team.pendingApprovalDesc')"
      type="warning"
      :closable="false"
      show-icon
      class="pending-alert"
    />

    <!-- 团队描述 -->
    <el-card v-if="currentTeam?.description" class="description-card" shadow="never">
      <template #header>
        <span>{{ $t('team.teamDescription') }}</span>
      </template>
      <p class="description-text">{{ currentTeam.description }}</p>
    </el-card>

    <!-- 主要内容区域 - Tab导航 -->
    <div class="main-content">
      <el-tabs v-model="activeTab" class="team-tabs" @tab-change="handleTabChange">
        <!-- 团队概览 Tab -->
        <el-tab-pane :label="$t('team.overview')" name="overview">
          <div class="tab-content">
            <el-row :gutter="24">
              <!-- 左侧：团队成员 -->
              <el-col :span="16">
                <TeamMemberList
                  :team-id="teamId"
                  :can-manage="canManage"
                  @member-updated="handleMemberUpdated"
                />
              </el-col>

              <!-- 右侧：团队信息和邀请码 -->
              <el-col :span="8">
                <!-- 团队统计 -->
                <el-card class="stats-card" shadow="never">
                  <template #header>
                    <span>{{ $t('team.teamStats') }}</span>
                  </template>
                  <div class="stats-grid">
                    <div class="stat-item">
                      <div class="stat-value">{{ currentTeam?.currentMembers || 0 }}</div>
                      <div class="stat-label">{{ $t('team.totalMembers') }}</div>
                    </div>
                    <div class="stat-item">
                      <div class="stat-value">{{ formatDate(currentTeam?.createdAt) }}</div>
                      <div class="stat-label">{{ $t('team.createdDate') }}</div>
                    </div>
                    <div class="stat-item">
                      <div class="stat-value">{{ memberPercentage }}%</div>
                      <div class="stat-label">{{ $t('team.memberUsage') }}</div>
                    </div>
                  </div>
                </el-card>

                <!-- 邀请码管理 -->
                <TeamInviteCodeList
                  v-if="canManage"
                  :team-id="teamId"
                  class="invite-codes-card"
                />
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 项目看板 Tab -->
        <el-tab-pane :label="$t('project.kanban')" name="kanban">
          <div class="tab-content">
            <ProjectKanban
              :team-id="teamId"
              :can-manage="canManage"
              @project-updated="handleProjectUpdated"
            />
          </div>
        </el-tab-pane>

        <!-- 任务管理 Tab -->
        <el-tab-pane :label="$t('project.taskManagement')" name="tasks">
          <div class="tab-content">
            <TaskManagement
              :team-id="teamId"
              :can-manage="canManage"
              @task-updated="handleTaskUpdated"
            />
          </div>
        </el-tab-pane>

        <!-- 公告通知 Tab -->
        <el-tab-pane :label="$t('project.announcements')" name="announcements">
          <div class="tab-content">
            <AnnouncementSystem
              :team-id="teamId"
              :can-manage="canManage"
              @announcement-updated="handleAnnouncementUpdated"
            />
          </div>
        </el-tab-pane>

        <!-- 团队聊天 Tab -->
        <el-tab-pane :label="$t('team.chat')" name="chat">
          <div class="tab-content chat-tab-content">
            <TeamChatRoom
              :team-id="teamId"
              :current-team="currentTeam"
            />
          </div>
        </el-tab-pane>

      </el-tabs>
    </div>

    <!-- 编辑团队对话框 -->
    <EditTeamDialog
      v-model="showEditDialog"
      :team="currentTeam"
      @success="handleEditSuccess"
    />

    <!-- 邀请成员对话框 -->
    <InviteMemberDialog
      v-model="showInviteDialog"
      :team-id="teamId"
      @success="handleInviteSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  Edit,
  User,
  UserFilled,
  MoreFilled,
  Setting,
  Delete
} from '@element-plus/icons-vue'
import { useTeamStore } from '@/stores/teamStore'
import { useAuthStore } from '@/stores/auth'
import { getTeamStatusLabel, getTeamStatusType } from '@/types/team'
import { formatDate } from '@/utils/date'
import TeamMemberList from '@/components/team/TeamMemberList.vue'
import TeamInviteCodeList from '@/components/team/TeamInviteCodeList.vue'
import EditTeamDialog from '@/components/team/EditTeamDialog.vue'
import InviteMemberDialog from '@/components/team/InviteMemberDialog.vue'
// 项目管理组件
import ProjectKanban from '@/components/project/ProjectKanban.vue'
import TaskManagement from '@/components/project/TaskManagement.vue'
import AnnouncementSystem from '@/components/project/AnnouncementSystem.vue'
// 团队聊天组件
import TeamChatRoom from '@/views/team/components/TeamChatRoom.vue'

const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const teamStore = useTeamStore()
const authStore = useAuthStore()

// 响应式数据
const showEditDialog = ref(false)
const showInviteDialog = ref(false)
const activeTab = ref('overview') // 当前激活的Tab

// 计算属性
const teamId = computed(() => Number(route.params.id))
const currentTeam = computed(() => teamStore.currentTeam)

const memberPercentage = computed(() => {
  if (!currentTeam.value) return 0
  return Math.round((currentTeam.value.currentMembers / currentTeam.value.maxMembers) * 100)
})

const canManage = computed(() => {
  // 只有团队状态为APPROVED或ACTIVE时才能管理
  const isTeamApproved = currentTeam.value?.status === 'APPROVED' || currentTeam.value?.status === 'ACTIVE'

  // 检查当前用户在团队中的角色
  const currentUserId = authStore.user?.id
  if (!currentUserId) return false

  const currentMember = teamStore.teamMembers.find(member => member.userId === currentUserId)
  const hasPermission = currentMember?.role === 'OWNER' || currentMember?.role === 'ADMIN'

  return isTeamApproved && hasPermission
})

const canDelete = computed(() => {
  // 只有团队所有者可以删除团队
  const currentUserId = authStore.user?.id
  if (!currentUserId) return false

  const currentMember = teamStore.teamMembers.find(member => member.userId === currentUserId)
  return currentMember?.role === 'OWNER'
})



// 方法
const goBack = () => {
  router.push('/dashboard/team')
}

const handleCommand = async (command: string) => {
  switch (command) {
    case 'settings':
      // 跳转到团队设置页面
      router.push(`/dashboard/team/${teamId.value}/settings`)
      break
    case 'delete':
      try {
        await teamStore.deleteTeam(teamId.value)
        ElMessage.success(t('team.deleteSuccess'))
        goBack()
      } catch (error) {
        console.error('删除团队失败:', error)
      }
      break
  }
}

const handleEditSuccess = () => {
  showEditDialog.value = false
  ElMessage.success(t('team.updateSuccess'))
}

const handleInviteSuccess = () => {
  showInviteDialog.value = false
  ElMessage.success(t('team.inviteSuccess'))
}

const handleMemberUpdated = () => {
  // 成员更新后刷新团队信息
  fetchTeamDetail()
}

// 项目管理相关事件处理
const handleTabChange = (tab: string) => {
  // 保存当前激活的Tab到URL参数
  router.replace({
    query: {
      ...route.query,
      tab: tab
    }
  })
}

const handleProjectUpdated = () => {
  // 项目更新后的处理逻辑
  ElMessage.success(t('project.updateSuccess'))
}

const handleTaskUpdated = () => {
  // 任务更新后的处理逻辑
  ElMessage.success(t('project.taskUpdateSuccess'))
}

const handleAnnouncementUpdated = () => {
  // 公告更新后的处理逻辑
  ElMessage.success(t('project.announcementUpdateSuccess'))
}

const fetchTeamDetail = async () => {
  try {
    await teamStore.fetchTeamDetail(teamId.value)
  } catch (error) {
    console.error('获取团队详情失败:', error)
    ElMessage.error(t('team.fetchDetailError'))
    goBack()
  }
}

// 生命周期
onMounted(() => {
  fetchTeamDetail()

  // 从URL参数恢复Tab状态
  const tabFromQuery = route.query.tab as string
  if (tabFromQuery && ['overview', 'kanban', 'tasks', 'announcements', 'chat'].includes(tabFromQuery)) {
    activeTab.value = tabFromQuery
  }
})

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    fetchTeamDetail()
  }
})
</script>

<style scoped lang="scss">
.team-detail {
  padding: 24px;
  background: var(--el-bg-color-page);
  min-height: 100vh;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;

      .team-info {
        display: flex;
        align-items: center;
        gap: 16px;

        .team-meta {
          .team-name {
            margin: 0 0 8px 0;
            font-size: 24px;
            font-weight: 600;
            color: var(--el-text-color-primary);
          }

          .team-status {
            display: flex;
            align-items: center;
            gap: 12px;

            .member-count {
              font-size: 14px;
              color: var(--el-text-color-regular);
            }
          }
        }
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .description-card {
    margin-bottom: 24px;

    .description-text {
      margin: 0;
      line-height: 1.6;
      color: var(--el-text-color-regular);
    }
  }

  .main-content {
    .team-tabs {
      background: var(--el-bg-color);
      border-radius: 8px;
      padding: 0;

      :deep(.el-tabs__header) {
        margin: 0;
        padding: 0 24px;
        background: var(--el-bg-color);
        border-bottom: 1px solid var(--el-border-color-light);
        border-radius: 8px 8px 0 0;
      }

      :deep(.el-tabs__nav-wrap) {
        padding: 16px 0;
      }

      :deep(.el-tabs__item) {
        font-size: 16px;
        font-weight: 500;
        padding: 0 24px;
        height: 40px;
        line-height: 40px;

        &.is-active {
          color: var(--el-color-primary);
        }
      }

      :deep(.el-tabs__content) {
        padding: 0;
      }

      .tab-content {
        padding: 24px;
        min-height: 500px;
      }
    }

    .stats-card {
      margin-bottom: 24px;

      .stats-grid {
        display: grid;
        grid-template-columns: 1fr;
        gap: 16px;

        .stat-item {
          text-align: center;
          padding: 12px;
          background: var(--el-bg-color-page);
          border-radius: 8px;

          .stat-value {
            font-size: 20px;
            font-weight: 600;
            color: var(--el-color-primary);
            margin-bottom: 4px;
          }

          .stat-label {
            font-size: 12px;
            color: var(--el-text-color-secondary);
          }
        }
      }
    }

    .invite-codes-card {
      margin-top: 24px;
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .team-detail {
    .main-content {
      .el-row {
        .el-col {
          &:first-child {
            margin-bottom: 24px;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .team-detail {
    padding: 16px;

    .page-header {
      flex-direction: column;
      gap: 16px;

      .header-left {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;

        .team-info {
          .team-meta {
            .team-name {
              font-size: 20px;
            }

            .team-status {
              flex-direction: column;
              align-items: flex-start;
              gap: 8px;
            }
          }
        }
      }

      .header-right {
        width: 100%;
        justify-content: flex-end;
      }
    }

    .main-content {
      .el-row {
        .el-col {
          width: 100% !important;
          max-width: 100% !important;
        }
      }
    }
  }
}
</style>
